<template>
    <a-form :form="form">
        <a-form-item style="display: none">
            <a-input v-decorator="['id']"/>
            <a-input v-decorator="['isDialog']"/>
        </a-form-item>
        <a-collapse v-model="panelActiveKeys" expandIconPosition="right" class="aCollapse">
            <a-collapse-panel key="1" :header="i18n('list.infomation','基本信息')" class="cp-box">
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.name','名称')">
                          <rx-input-i18n :placeholder="i18n('form.name','名称')" @blur="getPinyinByName"
                                         v-decorator="['i18nJson', {rules: [{required: true, message: i18n('form.name','名称','input')}]}]"
                          />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.markKey','标识键')">
                            <a-input :placeholder="i18n('form.markKey','标识键')"
                                     v-decorator="['key', {rules: [{required: true, message: i18n('form.markKey','标识键','input')}]}]"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.editForm','表单方案(编辑)')">
                            <rx-input-button ref="formAlias" style="width: 100%;" class="input-button-edit"
                                             @click="selectSolution2"
                                             v-decorator="['formAlias']"
                            ></rx-input-button>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.newForm','表单方案(新增)')">
                            <rx-input-button ref="formAddAlias" style="width: 100%;" class="input-button-edit"
                                             @click="selectSolution1"
                                             v-decorator="['formAddAlias']"
                            ></rx-input-button>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.classify','分类')"
                                     class="rx-form-item">
                            <rx-category-select cat-key="FORM" :isGrant="true" v-show="isShowManageTree"
                                                :isAdmin="isManageToTree"
                                                v-decorator="['treeId', {rules: [{required: true, message: i18n('form.classify','请选择分类','select')}]}]"></rx-category-select>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-collapse-panel>
            <a-collapse-panel key="2" :header="i18n('list.paraConfig','参数配置')" class="cs-setting">
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.multiSelect','是否多选')">
                            <a-switch v-model="multiSelect"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.childNodes','是否仅选择子节点')">
                            <a-switch v-model="onlySelLeaf"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.lazyLoad','是否懒加载')">
                            <a-switch v-model="isLazy"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.expand','是否展开(0为不展开)')">
                            <a-input-number style="width:100%;" :placeholder="i18n('form.expandLevel','展开等级')"
                                            v-decorator="['expandLevel']" :min="0" :max="10" :default-value="1"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.openNode','开启根节点')">
                            <a-switch v-model="openNode"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.parentIdValue','第一级父ID值')">
                            <a-input v-decorator="['parentIdValue']"/>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-collapse-panel>
            <a-collapse-panel key="3" :header="i18n('list.dataSource','数据来源')">
                <a-row>
                    <a-col :span="12" v-if="(useCondSqlType=='NO' || useCondSqlType=='YES') && !isTenant">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.dataSource','数据源')">
                              <rx-input-button style="width: 100%;" class="input-button-edit" @click="openDataSource"
                                               v-decorator="['dbAs']"
                              ></rx-input-button>
                        </a-form-item>
                    </a-col>
                </a-row>
              <a-row>
                <a-col :span="12">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.SQlMode','SQL构建方式')">
                    <a-radio-group :placeholder="i18n('form.SQlMode','SQL构建方式')" v-decorator="['useCondSql']" @change="userCondSqlChange">
                      <a-radio value="NO">SQL(FreeMarker)</a-radio>
                      <a-radio value="YES">SQL(Groovy)</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-item v-show="useCondSqlType=='NO'" :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                               :label="i18n('form.SQL','SQL语句') + '(Freemarker)'" class="labelText">

                    <rx-monaco-editor
                        ref="sql"
                        :key="key"
                        v-decorator="['sql', {rules: [{required: false, message: $ti18('rxDecorator.input','请输入') + 'SQL'}]}]"
                        language="sql"
                        style="height:300px;"
                    >
                      <template v-slot:monacoeditor>
                        <div>
                          <a-dropdown>
                            <a-menu slot="overlay" @click="onSqlExp($event,'sql')">
                              <a-menu-item key="{CREATE_BY_}">{{i18n('currUser','当前用户')}}ID</a-menu-item>
                              <a-menu-item key="{DEP_ID_}">{{i18n('currDepart','当前部门')}}ID</a-menu-item>
                              <a-menu-item key="{TENANT_ID_}">{{i18n('currOrgan','当前机构')}}ID</a-menu-item>
                              <a-menu-item key="{COMPANY_ID_}">{{i18n('currCompany','当前公司')}}ID</a-menu-item>
                              <a-menu-item key="{menuId}">{{i18n('currMenu','当前菜单')}}ID</a-menu-item>
                            </a-menu>
                            <a-button style="margin-right: 8px">{{i18n('insertSQL','插入上下文的SQL条件参数')}}
                              <a-icon type="down"/>
                            </a-button>
                          </a-dropdown>
                          <a-dropdown >
                            <a-menu slot="overlay"  >
                              <template v-for="item in constantField">
                                <a-menu-item :key="item.value"
                                             @click="sqlInsertChange(item.value,'sql')"
                                             v-if="!item.children"> {{item.label}}
                                </a-menu-item>
                              </template>
                            </a-menu>
                            <a-button style="margin-right: 8px">{{i18n('form.insertConstant','插入常量')}}
                              <a-icon type="down"/>
                            </a-button>
                          </a-dropdown>
                          <a-button style="margin-right: 8px" @click="insertExp('/*TABLE*/','sql')">{{i18n('list.tableForm','表单占位符')}}</a-button>
                          <a-button style="margin-right: 8px" @click="insertExp('/*CONDITION*/','sql')">{{i18n('list.condition','条件占位符')}}</a-button>
                          <a-button style="margin-right: 8px" @click="insertExp('/*ORDERBY*/','sql')">{{i18n('list.sortPlace','排序占位符')}}</a-button>
                          <a-button style="margin-left: 8px" @click="onRun()" type="primary">{{ i18n('list.execute', '执行') }}</a-button>
                        </div>
                      </template>
                    </rx-monaco-editor>
                  </a-form-item>
                  <a-form-item v-show="useCondSqlType=='YES'" :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                               :label="i18n('list.buildSQL','构建SQL(Groovy)语句')">
                    <rx-monaco-editor
                        ref="condSqls"
                        :key="key"
                        v-decorator="['condSqls', {rules: [{required: false, message: $ti18('rxDecorator.input','请输入') + 'SQL'}]}]"
                        language="java"
                        style="height:300px;"
                    >
                      <template v-slot:monacoeditor>
                        <div>
                          <a-button style="margin-right: 8px" @click="showScriptDialog()">{{i18n('list.fastScript','快速脚本')}}</a-button>
                          <a-dropdown>
                            <a-menu slot="overlay" @click="onSqlExp($event,'condSqls')">
                              <a-menu-item key="{CREATE_BY_}">{{i18n('currUser','当前用户')}}ID</a-menu-item>
                              <a-menu-item key="{DEP_ID_}">{{i18n('currDepart','当前部门')}}ID</a-menu-item>
                              <a-menu-item key="{TENANT_ID_}">{{i18n('currOrgan','当前机构')}}ID</a-menu-item>
                              <a-menu-item key="{COMPANY_ID_}">{{i18n('currCompany','当前公司')}}ID</a-menu-item>
                              <a-menu-item key="{menuId}">{{i18n('currMenu','当前菜单')}}ID</a-menu-item>
                            </a-menu>
                            <a-button style="margin-right: 8px">{{i18n('insertSQL','插入上下文的SQL条件参数')}}
                              <a-icon type="down"/>
                            </a-button>
                          </a-dropdown>
                          <a-dropdown >
                            <a-menu slot="overlay"  >
                              <template v-for="item in constantField">
                                <a-menu-item :key="item.value"
                                             @click="sqlInsertChange(item.value,'condSqls')"
                                             v-if="!item.children"> {{item.label}}
                                </a-menu-item>
                              </template>
                            </a-menu>
                            <a-button style="margin-right: 8px">{{i18n('form.insertConstant','插入常量')}}
                              <a-icon type="down"/>
                            </a-button>
                          </a-dropdown>
                          <a-button style="margin-right: 8px" @click="insertExp('/*TABLE*/','condSqls')">{{i18n('list.tableForm','表单占位符')}}</a-button>
                          <a-button style="margin-right: 8px" @click="insertExp('/*CONDITION*/','condSqls')">{{i18n('list.condition','条件占位符')}}</a-button>
                          <a-button style="margin-right: 8px" @click="insertExp('/*ORDERBY*/','condSqls')">{{i18n('list.sortPlace','排序占位符')}}</a-button>
                          <a target="_blank" href="https://alidocs.dingtalk.com/i/p/Dnb9XJlQxLaGyAp7pLmkQxNgpMV9Qz2g">
                            <a-icon type="question-circle" />
                          </a>
                          <a-button style="margin-left: 8px" @click="onRun()" type="primary">{{ i18n('list.execute', '执行') }}</a-button>
                        </div>
                      </template>
                    </rx-monaco-editor>
                  </a-form-item>
                </a-col>
              </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <span slot="label">
                                {{i18n('form.valueField','值字段')}}
                                <a-tooltip >
                                    <span slot="title">{{i18n('form.valueFieldTips','设置树对应的值字段，一般选择唯一性字段，如：主键')}}</span>
                                    <a-icon type="question-circle" />
                                </a-tooltip>
                            </span>
                            <a-select :placeholder="i18n('form.valueField','值字段')" allowClear :options="fieldsDatas"
                                      v-decorator="['idField', {rules: [{required: true, message: i18n('form.valueField','值字段','input')}]}]"></a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <span slot="label">
                                {{ i18n('form.displayField', '显示字段') }}
                                <a-tooltip >
                                    <span slot="title">{{i18n('form.displayFieldTips', '设置树显示的字段值，选择易于给客户理解的名称字段，如：合同名称')}}</span>
                                    <a-icon type="question-circle" />
                                </a-tooltip>
                            </span>

                            <a-select :placeholder="i18n('form.displayField','显示字段')" allowClear :options="fieldsDatas"
                                      v-decorator="['textField', {rules: [{required: true, message: i18n('form.displayField','显示字段','input')}]}]"></a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.parentField','父ID字段')">
                            <a-select :placeholder="i18n('form.parentField','父ID字段')" allowClear :options="fieldsDatas"
                                      v-decorator="['parentField']"></a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <span slot="label">
                                {{ i18n('form.publishField','发布字段') }}
                                <a-tooltip >
                                    <span slot="title">{{ i18n('form.publishFieldTips', '点击树的某一节点，所传递出去的参数') }}</span>
                                    <a-icon type="question-circle" />
                                </a-tooltip>
                            </span>
                            <a-select :placeholder="i18n('form.publishField','发布字段')" allowClear
                                      mode="tags"
                                      :options="fieldsDatas"
                                      label-in-value
                                      v-decorator="['publishConf']"></a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                                     :label="$ti18('rxForm.describe','描述')">
                            <a-textarea :placeholder="$ti18('rxForm.describe','描述')" v-decorator="['descp']" :rows="4"/>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-collapse-panel>
            <a-collapse-panel key="4" :header="i18n('form.basicStyle','基础风格')">
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.height','高度')">
                            <a-input-number style="width:100%;" :placeholder="i18n('form.height','高度')"
                                            v-decorator="['height']" :min="100" :max="1500"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.width','宽度')">
                            <a-input-number style="width:100%;" :placeholder="i18n('form.width','宽度')"
                                            v-decorator="['width']" :min="100" :max="1500"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.treeStyle','树形风格样式')">
                            <TreeStyleSelect v-model="treeStyle"/>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-collapse-panel>
        </a-collapse>
    </a-form>
</template>

<script>
import FormBoListApi from '@/api/form/core/formBoList'
import {BaseForm, Dialog,RxInputButton, RxMonacoEditor, Util, JsConstant} from "@lowcode/jpaas-common-lib";
import DialogBox from "../../../../assets/js/DialogBox";
import FormBoEntityApi from "../../../../api/form/bo/formBoEntity";
import TreeStyleSelect from "@/views/modules/form/core/TreeStyle/TreeStyleSelect";
import AppName from "@/assets/js/AppName.js";
import FormCustomQueryApi from "@/api/form/core/formCustomQuery";

export default {
    name: "FormBoListTreeEdit1",
    props: ["isDialog", "curAppObj"],
    mixins: [BaseForm,AppName],
    components: {
        RxMonacoEditor, TreeStyleSelect,RxInputButton
    },
    data() {
        return {
            panelActiveKeys: ['1', '2', '3', '4'],
            complexJson: {
              main: {
                formAlias: {text: "formName", value: "formAlias"},
                formAddAlias: {text: "formAddName", value: "formAddAlias"},
                dbAs: {text: "dbAs", value: "dbAs"}
              }
            },
            useCondSqlType: "NO",
            isTenant:false,
            labelCol2: {span: 3},
            labelCol3: {span: 8},
            wrapperCol1: {span: 19},
            fieldsJson: [],
            fieldsDatas: [],
            multiSelect: true,
            onlySelLeaf: false,
            isLazy: false,
            openNode: true,
            treeStyle: {},
            constantField: [],
            key:Util.randomId()
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
        this.loadConstants();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formBoListDialog", key);
        },
      //获取常量字段
      loadConstants() {
        FormCustomQueryApi.getConstants().then(data => {
          this.constantField = this.constantField.concat(data.map(item => {
            return {label: item.val, value: item.key}
          }));
        })
      },
        selectSolution(vm, callback) {
            var config = {curVm: this, widthHeight: ['1000px', '600px'], data: {multiSelect: false}};
            DialogBox.openSoution(config, function (data) {
                if (callback) {
                    callback(data);
                }
                vm.setVal(data.alias, data.name)
            })
        },
        selectSolution1(vm) {
            this.selectSolution(vm);
        },
        selectSolution2(vm) {
            var self = this;
            this.selectSolution(vm, function (data) {
                if(!self.form.getFieldValue('name')
                    &&  !self.form.getFieldValue('key')){
                  var mdl = Object.assign(self.form.getFieldsValue(), {
                    i18nJson: data.name + self.i18n('List','列表'),
                    key: data.alias + '_treelist'
                  });
                  self.form.setFieldsValue(mdl);
                }

                if (data.bodefId) {
                    FormBoEntityApi.getMainExcludeAttrsByBoDefId(data.bodefId).then(res => {
                        if (res.data && !self.form.getFieldValue('sql')) {
                            var str = 'select * from ' + res.data.tableName;
                            self.$refs.sql.insertContent(str);
                        }
                    })
                }
            });
        },
      onSqlExp(e,type) {
        this.$refs[type].insertContent("$" + e.key);
      },
      insertExp(text,type) {
        this.$refs[type].insertContent(text);
      },
      //点击某个常量触发
      sqlInsertChange(value,type) {
        this.$refs[type].insertContent(value);
      },
        get(id) {
            return FormBoListApi.get(id);
        },
        save(values) {
            if (this.mdl.fieldsJson) {
                var oldFieldsJson = {};
                JSON.parse(this.mdl.fieldsJson).forEach(item => {
                    oldFieldsJson[item.field] = item.isReturn;
                });
                this.fieldsJson.forEach(item => {
                    if (oldFieldsJson.hasOwnProperty(item.field)) {
                        item.isReturn = oldFieldsJson[item.field];
                    }
                })
            }
            values.fieldsJson = JSON.stringify(this.fieldsJson);
            values.publishConf = JSON.stringify(values.publishConf);
            values.isTreeDlg = 'YES';
            values.multiSelect = this.multiSelect ? 'YES' : 'NO';
            values.onlySelLeaf = this.onlySelLeaf ? 'YES' : 'NO';
            values.isLazy = this.isLazy ? 'YES' : 'NO';
            values.openNode = this.openNode ? 'YES' : 'NO';
            values.treeStyle = JSON.stringify(this.treeStyle) ;
            if (!values.formAlias) {
                values.formName = "";
            }
            if (!values.formAddAlias) {
                values.formAddName = "";
            }
            if(this.isTenant){
              values.isTenant="1";
              values.dbAs="";
            }else {
              values.isTenant="0";
            }
            //新增时保存应用ID
            let appId = this.curAppObj.appId;
            if (appId && !this.pkId) {
                values.appId = appId;
            }
            return FormBoListApi.save(values);
        },
        handleSubmit(self, this_) {
            this_.form.validateFields((err, values) => {
                if (err) {
                    return;
                }
                values.pkId = this_.pkId;
                this_.confirmLoading = true;
                if (this_.validForm) {
                    var flag = this_.validForm(values);
                    if (!flag) {
                        return;
                    }
                }
                this_.onSubmit(values);
                this_.save(values).then(res => {
                    if (res.success && res.code == 200) {
                        self.pkId = res.data.pkId;
                        self.currentView = self.edit2;
                        self.currentName = "edit2";
                        self.oktext = self.$ti18('rxForm.saveBtn', '保存');
                    }
                }).catch(() => {
                    this_.$message.error(self.$ti18('rxMsa.sysError', '系统错误，请稍后再试!'))
                }).finally(() => {
                    this_.confirmLoading = false
                })
            })
        },
        onload_(values) {
            if (values) {
                values.useCondSql = values.useCondSql || "NO";
                this.useCondSqlType = values.useCondSql;
                values.condSqls = values.condSqls ? values.condSqls : "";
                this.onRun(Util.deepClone(values));
                var conf = values.publishConf || "[]";
                values.publishConf = JSON.parse(conf);
                this.multiSelect = values.multiSelect == 'YES';
                this.onlySelLeaf = values.onlySelLeaf == 'YES';
                this.isLazy = values.isLazy == 'YES';
                this.openNode = values.openNode == 'YES';
                if(values.treeStyle) {
                    this.treeStyle = JSON.parse(values.treeStyle)
                }
                this.isTenant=values.isTenant=="1"?true:false;
                return;
            }
            //默认值
            var data = {
                isDialog: this.isDialog,
                useCondSql:"NO",
                height: 350,
                width: 650,
                expandLevel: 1,
            };
            this.mdl = Object.assign(data);
            this.form.setFieldsValue(this.mdl)
        },
        openDataSource(vm) {
            Dialog.openDataSourceDialog({
                curVm: this, widthHeight: ['1200px', '600px'],
                data: {appName: this.serviceName, curAppObj: this.curAppObj}
            }, function (self, data) {
                vm.setVal(data.alias, data.name);
            })
        },
        showScriptDialog(){
          let self=this;
          let config={curVm:this};
          Dialog.openScriptDialog(config,function (script){
            self.$refs.condSqls.insertContent(script);
          })
        },
        userCondSqlChange(e) {
          this.key=Util.randomId();
          this.useCondSqlType = e.target.value;
          this.mdl.useCondSql = e.target.value;
        },
        onRun(values) {
            if (!values) {
                values = this.form.getFieldsValue();
                delete values.publishConf;
            }
            this.onSubmit(values);
            FormBoListApi.onRun(values).then(res => {
                if (res.success) {
                    res.data.fieldColumns.forEach(item => {
                        item.isReturn = false;
                    })
                    this.fieldsJson = res.data.fieldColumns;
                    this.fieldsDatas = res.data.fieldColumns.map(field => {
                        return {label: field.header, value: field.field}
                    });
                }
            })
        },
        getPinyinByName() {
            let i18nJson = this.form.getFieldsValue().i18nJson
            if (!this.$i18(i18nJson)) {
                return;
            }
            if (this.form && this.form.getFieldsValue().key) {
                return;
            }
            this.getPinyin(this.$i18(i18nJson)).then(res => {
                //去除不可见的特殊符号
                if (res) {
                    res = res.replace(/\u200B/g, '');
                }
                this.form.setFieldsValue({key: res})
            })
        }
    },
    watch: {
        treeStyle :{
            handler(v){
                console.log('tree',v)
            },
            deep:true
        }
    }
}
</script>

<style>
.aCollapse .ant-collapse-content {
    overflow: initial !important;
}

.ingpusty input {
    background-color: #FFFFFF !important;
    width: calc(100% - 60px) !important;
}

.rx-form-item {
    display: flex;
}

.rx-form-item >>> .ant-form-item-control-wrapper {
    flex: 1;
}

.input-button-edit {
  margin-top: 6px;
}
</style>